package com.stdz.counter.core.pool;

import com.sun.org.apache.xpath.internal.operations.Mod;
import de.re.easymodbus.modbusclient.ModbusClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 *
 */
public class ClientPool {

    private static transient Logger logger = LoggerFactory.getLogger(ClientPool.class);

    private Map<String, ModbusClient> pool;

    private ClientPool() {
        this.pool = new ConcurrentHashMap<String, ModbusClient>();
    }

    private static ClientPool instance = new ClientPool();

    public static ClientPool getInstance() {
        return instance;
    }

    public ModbusClient createModbusClient(String comPort) {
        ModbusClient modbusClient = new ModbusClient();
        if (this.pool.containsKey(comPort)) {
            logger.error("cannot create modbus client, still one thread use");
            return null;
        }
        try {
            modbusClient.setConnectionTimeout(10000);
            modbusClient.Connect(comPort);
        } catch (Throwable e) {
            logger.error("create modbus client error:", e);
            return null;
        }
        pool.put(comPort, modbusClient);
        return modbusClient;
    }

    public ModbusClient getModbusClient(String comPort) {
        if (pool.containsKey(comPort)) {
            return pool.get(comPort);
        }
        return null;
    }

    public void releaseModbusClient(String comPort, ModbusClient modbusClient) {
        if (modbusClient == null) {
            return;
        }
        try {
            if (modbusClient.isConnected()) {
                modbusClient.Disconnect();
            }
        } catch (IOException e) {
            logger.error("close modbus client connection error:{}", e);
        } finally {
            pool.remove(comPort);
        }
    }
}
